import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/foundation.dart';
import 'package:hm_pda_app/config/http_request.dart';
import 'package:hm_pda_app/config/password_encryptor.dart';
import 'package:hm_pda_app/config/jsencrypt.dart';
import 'dart:convert';
import 'package:flutter/material.dart';

// import 'package:hm_pda_app/config/environment.dart';
class User {
  final String tenantId;
  final String username;
  final String password;
  final String clientId;
  final String grantType;
  final bool rememberMe;

  User({
    required this.tenantId,
    required this.username,
    required this.password,
    required this.clientId,
    required this.grantType,
    required this.rememberMe,
  });

  // 手动实现 toJson 方法
  Map<String, dynamic> toJson() {
    return {
      'tenantId': tenantId,
      'username': username,
      'password': password,
      'clientId': clientId,
      'grantType': grantType,
      'rememberMe': rememberMe,
    };
  }
}

// 登录成功后的实体
class LoginInfo {
  final bool isAdmin;
  final String accessToken;

  LoginInfo({required this.accessToken, required this.isAdmin});

  Map<String, dynamic> toJson() {
    return {'access_token': accessToken, 'isAdmin': isAdmin};
  }
}

class AuthProvider with ChangeNotifier {
  bool _isLoggedIn = false;
  String? _token;

  bool get isLoggedIn => _isLoggedIn;
  String? get token => _token;

  Future<bool> login(String username, String password) async {
    try {
    
      final loginData = User(
        tenantId: "000000",
        username: username,
        password:password,
        clientId: "e5cd7e4891bf95d1d19206ce24a7b32e",
        grantType: "password",
        rememberMe: true,
      );
      final asekey = PasswordEncryptor.generateRandomString();
      final response = await HttpUtil.post(
        '/auth/login',

        data: PasswordEncryptor.encryptWithAes(
          asekey,
          jsonEncode(loginData.toJson()),
        ),
        headers: {
          'isToken': false,
          'isEncrypt': true,
          'encrypt-key': encryptWithRSAPublicKey(
            'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdHnzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ==',
            PasswordEncryptor.encryptBase64(asekey),
          ),
        },
        // data:'NW6se77hW322bCJ7F40QXhb2bsMnHsLrUbZGGuv8vdx3URrN0Ir+1icQpynLWCpN/9UWv5Ng1V6bZ9qL5ot8eZqYUxXuV4PhxPzkziEYFj6cwrPNm1Uxjdylk351VeazIdvzz7abgFW3FUNVnyU3CBUGBpIjfGNL7fULsBs4C7kTFBLktZYxfGOAK9o9Acjb84ZNpmNh0zSb3WtfZT+YtLfBRSY7UOmZ4fYLy/fxb7l+J4ZnT/br4uVj3RNyycubMo2++4rYf5inyVdYNP1ceQ=='
      );
      // 格式化响应数据为LoginInfo格式
      final loginInfo = LoginInfo(
        accessToken: response.data['access_token'],
        isAdmin: response.data['isAdmin'] ?? false,
      );

      print('response--${loginInfo.accessToken}');
      // _token = response.token;
      _token = response.data['access_token'];
      _isLoggedIn = true;
      // 保存登录状态到本地
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('token', _token!);
      await prefs.setBool('isLoggedIn', true);
      await HttpUtil.initialize(
        token: _token, // 如果有的话
      );
      // 获取用户信息
      getuserInfo();
     // notifyListeners();
      final result = _token != null ? true : false;
      return result;
    } catch (e) {
      print('Login error: $e');
      _isLoggedIn = false;
      _token = null;
      notifyListeners();
      rethrow; // Re-throw so UI can handle the error
    }
  }

  Future<void> getuserInfo() async {
    var res = await HttpUtil.get('/system/user/getInfo');
    print('用户信息res--${res.data}');
    if (res.data['user'] !=null) {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('userInfo', jsonEncode(res.data['user']));
      final userInfo =  prefs.getString('userInfo');
      print('用户信息userInfo--$userInfo');
    }
  }

  Future<void> autoLogin() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString('token');
      final loggedIn = prefs.getBool('isLoggedIn') ?? false;

      if (token != null && loggedIn) {
        _token = token;
        _isLoggedIn = true;
      } else {
        _token = '';
        _isLoggedIn = false;
      }
      notifyListeners();
    } catch (e) {
      print('AutoLogin error: $e');
      _token = '';
      _isLoggedIn = false;
      notifyListeners();
    }
  }

  Future<void> logout() async {
    try {
      _isLoggedIn = false;
      _token = null;
      final prefs = await SharedPreferences.getInstance();
      await prefs.clear();
      await HttpUtil.post('/auth/logout');
       final token = prefs.getString('token');
      final loggedIn = prefs.getBool('isLoggedIn') ?? false;
      print('退出---$token,$loggedIn');
      notifyListeners();
    } catch (e) {
      print('Logout error: $e');
      // Still set logged out state even if SharedPreferences fails
      _isLoggedIn = false;
      _token = null;
      notifyListeners();
    }
  }
}
